<!--
 * @Description: 抽屉
 * @Author: DHL
 * @Date: 2022-01-18 13:57:11
 * @LastEditors: DHL
 * @LastEditTime: 2022-11-14 09:31:41
-->
<template>
  <el-drawer
    v-model="myState.visible"
    :title="title"
    :direction="direction"
    :size="size"
    :destroy-on-close="destroyOnClose"
    lock-scroll
    :append-to-body="appendToBody"
    :modal-class="`tw-drawer ${getSticky ? 'tw-overlay-sticky' : ''}`"
    @open="handleOpen"
    @close="handleClose"
  >
    <template #header v-if="myState.header">
      <slot name="header"></slot>
    </template>

    <template #default>
      <div
        class="tw-drawer__body"
        v-loading="loading"
        element-loading-background="var(--tw-mask-color)"
      >
        <slot></slot>
      </div>
    </template>

    <template #footer v-if="myState.footer">
      <slot name="footer"></slot>
      <div v-if="loading" class="tw-loading-mask"></div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
  import { defineComponent, nextTick, reactive, ref, unref, useSlots } from 'vue'

  interface Props {
    /**
     * 是否显示弹框
     * 默认值：false
     */
    modelValue: boolean

    /**
     * 标题
     * 默认值： ''
     */
    title?: string

    /**
     * 弹出方向
     */
    direction?: any

    /**
     * Drawer 窗体的大小
     * 默认值：30%
     */
    size?: string

    /**
     * 组件内弹出
     */
    sticky?: boolean

    /**
     * 自身是否插入至 body 元素上
     */
    appendToBody?: boolean

    /**
     * 关闭时销毁 Dialog 中的元素
     * 默认值：true
     */
    destroyOnClose?: boolean

    /**
     * loading
     */
    loading?: boolean
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    title: '',
    direction: 'rtl',
    size: '30%',
    sticky: true,
    appendToBody: false,
    destroyOnClose: true,
    loading: false
  })

  /**
   * 是否组件内弹出
   */
  const getSticky = computed(() => {
    if (props.appendToBody) {
      return false
    }
    return props.sticky
  })

  /**
   * 插槽集合
   */
  const slots = useSlots()

  /**
   * 状态
   */
  const myState = reactive({
    visible: false,
    header: false,
    footer: false
  })

  watch(
    () => props.modelValue,
    (newValue) => {
      myState.visible = newValue
    },
    {
      immediate: true
    }
  )

  if (slots.footer) {
    myState.footer = true
  }

  if (slots.header) {
    myState.header = true
  }

  const emit = defineEmits(['open', 'close'])

  /**
   * 打开的回调
   */
  function handleOpen() {
    emit('open')
  }

  /**
   * 关闭的回调
   */
  function handleClose() {
    emit('close')
  }
</script>

<style lang="scss"></style>
